const express = require('express')
const app = express()
const bodyParser = require('body-parser')

//处理静态资源
app.use(express.static('public'))

//处理参数
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extend: false}))

//设置允许跨域访问该服务器
app.all("*",function (req,res,next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'PUT,GET,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With');
  res.header('Access-Control-Allow-Headers', ['mytoken','Content-Type']);
  next()
})

//路由
// 接收ajax请求
app.get('/data',(req,res)=>{
  setTimeout(function () {
    res.send('Hello world')
  },500)
})

app.get('/data2',(req,res)=>{
  setTimeout(function () {
    res.send('Hello world2')
  },1500)
})

app.get('/data3',(req,res)=>{
  setTimeout(function () {
    res.send('Hello world3')
  },3000)
})

// 接收fetch请求
app.get('/fetch',(req,res)=>{
  res.send('fetch请求,id='+req.query.id)
})

app.get('/fetch2/:id',(req,res)=>{
  res.send('fetch2请求,id='+req.params.id)
})

app.delete('/fetch3/:id',(req,res)=>{
  res.send('fetch3请求,id='+req.params.id)
})

app.post('/fetch4',(req,res)=>{
  res.send(`fetch4请求,name=${req.body.name},age=${req.body.age}`)
})

app.put('/fetch5/:id',(req,res)=>{
  res.send(`fetch5请求,id=${req.params.id},name=${req.body.name},age=${req.body.age}`)
})

app.get('/fetch6',(req,res)=>{
  res.json({
    name:'zhaoliu',
    age:33
  })
})

// 接收axios请求
app.get('/axios',(req,res)=>{
  res.send(`axios请求get，id=${req.query.id}`)
})

app.get('/axios/:id',(req,res)=>{
  res.send(`axios请求get(restful)，id=${req.params.id}`)
})

app.delete('/axios',(req,res)=>{
  res.send(`axios请求delete，id=${req.query.id}`)
})

app.post('/axios',(req,res)=>{
  res.send(`axios提交post，name=${req.body.name},pwd=${req.body.pwd}`)
})

app.put('/axios/:id',(req,res)=>{
  res.send(`axios更新put，id=${req.params.id},name=${req.body.name},pwd=${req.body.pwd}`)
})

app.get('/axios-json',(req,res)=>{
  res.json({
    msg:'ok',
    status:200
  })
})

app.get('/async1',(req,res)=>{
  res.send('hello')
})

app.get('/async2',(req,res)=>{
  if(req.query.info==='hello'){
    res.send('ok')
  }else{
    res.send('error')
  }
})

app.listen(3000,function () {
  console.log('服务器启动成功....')
})
